<template>
  <div>
    <div class="app-container">
      <div>
        <!--        <el-steps :active="tab" finish-status="success" simple>
                  <el-step title="设计表单"/>
                  <el-step title="选择单位 "/>
                  <el-step title="设置时限"/>
                </el-steps>-->
        <el-row :gutter="20">
          <el-col :span="8">
            <div :style="{background:tab===1?'#1890ff':'#cee6ff'}" style="padding: 12px;text-align: center;">
              <el-row :gutter="5">
                <el-col :span="10" align="right">
                  <div
                    style="height: 25px;width: 25px;background-color: white;text-align: center;border-radius: 50%;line-height: 25px">
                    <b style="color: #00afff">1.</b>
                  </div>
                </el-col>
                <el-col :span="12" align="left">
                  <div style="height: 25px;text-align: left;line-height: 25px">
                    <b :style="{color:tab!==1?'#1890ff':'#ffffff'}">设计表单</b>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col :span="8">
            <div :style="{background:tab===2?'#1890ff':'#cee6ff'}" style="padding: 12px;text-align: center;">
              <el-row :gutter="5">
                <el-col :span="10" align="right">
                  <div
                    style="height: 25px;width: 25px;background-color: white;text-align: center;border-radius: 50%;line-height: 25px">
                    <b style="color: #00afff">2.</b>
                  </div>
                </el-col>
                <el-col :span="12" align="left">
                  <div style="height: 25px;text-align: left;line-height: 25px">
                    <b :style="{color:tab!==2?'#1890ff':'#ffffff'}">选择单位</b>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col :span="8">
            <div :style="{background:tab===3?'#1890ff':'#cee6ff'}" style="padding: 12px;text-align: center;">
              <el-row :gutter="5">
                <el-col :span="10" align="right">
                  <div
                    style="height: 25px;width: 25px;background-color: white;text-align: center;border-radius: 50%;line-height: 25px">
                    <b style="color: #00afff">3.</b>
                  </div>
                </el-col>
                <el-col :span="12" align="left">
                  <div style="height: 25px;text-align: left;line-height: 25px">
                    <b :style="{color:tab!==3?'#1890ff':'#ffffff'}">设定时限</b>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row>
        <el-col :span="24">
          <div v-if="tab===1" style="background: white;margin-top: 10px;height: 100%">
            <el-row>
              <el-col :span="12">
                <div style="padding: 10px">
                  <el-row :gutter="15">
                    <el-form ref="elForm" :model="formData" size="medium" label-width="90px" label-position="left">
                      <el-col :span="24">
                        <el-form-item label="表单名称" prop="formTitle"
                          :rules="{required: true, message: '表单名称', trigger: 'blur'}">
                          <el-input v-model="formData.formTitle" placeholder="请输入表单名称" :maxlength="20" show-word-limit
                            clearable prefix-icon='el-icon-s-order' :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col style="margin: 60px 10px 10px 10px" :span="16">
                        <span style="font-size: 15px;color: #d0cfcf">编辑问题</span>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item label="问题类型" :prop="'formlist['+formData.number+'].type'"
                          :rules="{required: true, message: '问题类型不能为空', trigger: 'blur'}">
                          <el-select v-model="formData.formlist[formData.number].type" placeholder="请选择问题类型" clearable
                            :style="{width: '100%'}">
                            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                              :value="item.value" :disabled="item.disabled"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="16" v-if="formData.formlist[formData.number].type===1">
                        <el-form-item label="问题类别" :prop="'formlist['+formData.number+'].category'"
                          :rules="{required: true, message: '问题类别不能为空', trigger: 'blur'}">
                          <el-select v-model="formData.formlist[formData.number].category" placeholder="请选择问题类别"
                            clearable filterable :style="{width: '100%'}">
                            <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.dictLabel"
                              :value="item.dictValue" :disabled="item.default"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="问题题目" :prop="'formlist['+formData.number+'].title'"
                          :rules="{required: true, message: '问题题目不能为空', trigger: 'blur'}">
                          <el-input v-model="formData.formlist[formData.number].title" type="textarea"
                            placeholder="请输入问题题目" :maxlength="255" :autosize="{minRows: 1, maxRows: 4}"
                            :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <div v-for="(domain, index) in formData.formlist[formData.number].optionlist" :key="domain.key"
                        v-if="formData.formlist[formData.number].type===1">
                        <el-col :span="12">
                          <el-form-item :label="'答案'+(index+1)"
                            :prop="'formlist['+formData.number+'].optionlist['+index+'].option'"
                            :rules="{required: true, message: '答案不能为空', trigger: 'blur'}">
                            <el-input v-model="domain.option" placeholder="请输入选择答案" clearable :style="{width: '100%'}">
                            </el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="2">
                          <el-form-item label="说明原因" prop="reason">
                            <el-switch v-model="domain.reason"></el-switch>
                          </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if="formData.formlist[formData.number].type===1">
                          <el-form-item size="large">
                            <el-button @click="reomoptionlist(index)">删除备选答案</el-button>
                          </el-form-item>
                        </el-col>
                      </div>
                      <el-col :span="8" v-if="formData.formlist[formData.number].type===1">
                        <el-form-item size="large">
                          <el-button @click="addoptionlist">添加备选答案</el-button>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item size="large">
                          <el-button @click="submitForm" type="primary" icon="el-icon-plus" size="medium"> 添加问题
                          </el-button>
                        </el-form-item>
                      </el-col>
                    </el-form>
                  </el-row>
                </div>
              </el-col>
              <el-col :span="12">
                <div style="padding: 10px">
                  <span style="font-size: 15px;color: #d0cfcf">表单预览</span>
                  <p style="color: #afafaf;text-align: center">{{ this.formData.formTitle }}</p>
                  <div v-for="(domain, index) in formData.formlist" :key="domain.key"
                    v-if="formData.formlist.length>1&&index+1!==formData.formlist.length">
                    <el-col :space="24" style="margin: 10px 0px"><span
                        style="color: #afafaf;">{{ index + 1 + "." + domain.title }}</span></el-col>
                    <div v-if="domain.type===1" style="margin-left: 20px">
                      <div v-for="(domainy, indey) in formData.formlist[index].optionlist" :key="domainy.key">
                        <el-col :span="24">
                          <el-radio size="large" disabled v-model="domainy.checked">{{
                              indey + 1 + '.' + domainy.option
                            }}
                          </el-radio>
                        </el-col>
                        <!--                        <el-col :space="24" v-if="domainy.reason">
                                                  <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    :disabled="true"
                                                    placeholder="请输入原因">
                                                  </el-input>
                                                </el-col>-->
                      </div>
                    </div>
                    <div v-else style="margin-left: 20px">
                      <el-col :space="24">
                        <el-input type="textarea" :rows="3" :disabled="true" placeholder="请输入回答">
                        </el-input>
                      </el-col>
                    </div>
                    <el-col :space="24">
                      <el-button type="danger" style="margin-left: 20px;margin-top: 10px" size="mini"
                        @click="reomopquestion(index)">删除问题
                      </el-button>
                      <el-button v-if="index!==0" type="primary" style="margin-left: 20px;margin-top: 10px" size="mini"
                        @click="mobilequestion(index,false)">上移问题
                      </el-button>
                      <el-button v-if="index!==formData.formlist.length-2" type="primary"
                        style="margin-left: 20px;margin-top: 10px" size="mini" @click="mobilequestion(index,true)">下移问题
                      </el-button>
                    </el-col>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div v-if="tab===2" style="background: white;margin-top: 10px;padding: 20px">
            <el-row>
              <el-col :span="24">
                <div>
                  <el-col :span="2">
                    快速选择
                  </el-col>
                  <el-checkbox-group v-model="schoolcategory" size="medium" @change="schoolchange">
                    <el-checkbox v-for="(item, index) in schoolOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-col>
              <el-col :span="24" style="margin-top: 20px">
                <el-transfer :titles="['可选择', '已选择']" @change="chooseSchool" v-model="schoolskey" :data="schoollist">
                </el-transfer>
              </el-col>
            </el-row>
          </div>
          <div v-if="tab===3" style="background: white;margin-top: 10px;padding: 20px">
            <el-row>
              <el-col :span="24">
                <div>
                  <el-col :span="2">
                    类型：
                  </el-col>
                  <el-col :span="22">
                    <el-radio v-model="timetype" :label=0>统一时间</el-radio>
                    <el-radio v-model="timetype" :label=1>定义时间</el-radio>
                  </el-col>
                </div>
                <el-col v-if="timetype===1" :span="13" v-for="(domain, index) in formData.schools"
                  style="margin-top: 25px;border: 1px solid #EDF1F2;" :key="domain.key">
                  <el-col :span="24" style="background: #EDF1F2;padding: 10px">
                    {{ domain.label }}
                  </el-col>
                  <el-col style="text-align: center;height: 100%;margin: 20px 20px 20px 0" :span="13">
                    <span style="line-height: 100%">选择时间：</span>
                    <el-date-picker type="datetime" v-model="domain.time" format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期选择" :picker-options="pickerOptions"
                      @change="handle(index,true)" clearable />
                  </el-col>
                </el-col>

                <el-col v-if="timetype===0" style="height: 100%;margin: 20px 20px 20px 0" :span="13">
                  <span style="line-height: 100%">选择时间：</span>
                  <el-date-picker type="datetime" v-model="time" format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期选择" :picker-options="pickerOptions"
                    @change="handle(time,false)" clearable />
                </el-col>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col style="background: white;text-align: end;padding: 15px" :span="24">
          <el-button v-if="tab>1" @click="addtab(false)">上一步</el-button>
          <el-button v-if="tab<3" type="primary" v-loading.fullscreen.lock="fullscreenLoading" @click="addtab(true)">
            下一步
          </el-button>
          <el-button v-if="tab===3" type="primary" @click="submitformdata">提交</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import {
    listSchool
  } from "@/api/patrol/school"
  import {
    addForm
  } from "@/api/patrol/form"

  export default {
    name: "addform",
    components: {},
    props: [],
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }

        },
        // 当前步骤
        tab: 1,
        // 当前步骤
        fullscreenLoading: false,
        // 时间的设置是统一还是单独
        timetype: 0,
        // 统一设置的时间，分别设置在学校对象里有一个time
        time: null,
        // 选中的学校类别
        schoolcategory: [],
        // 所以的学校，后端返回结构参照
        schoollist: [
          /*
                  {
                    key: 1,
                    label: `民办幼儿园 1`,
                    type: 0,
                    nature: true
                  },
                  {
                    key: 2,
                    label: `民办小学校 2`,
                    type: 1,
                    nature: true
                  }, {
                    key: 3,
                    label: `民办中学校 3`,
                    type: 2,
                    nature: true
                  }, {
                    key: 4,
                    label: `民办高中学校 4`,
                    type: 3,
                    nature: true
                  }, {
                    key: 5,
                    label: `公办中学校 5`,
                    type: 2,
                    nature: false
                  }, {
                    key: 6,
                    label: `公办高中学校 6`,
                    type: 4,
                    nature: false
                  }*/
        ],
        // 临时储存学校的key
        schoolskey: [],
        schoolOptions: [{
          "label": "幼儿园",
          "value": 0,
          disabled: false
        }, {
          "label": "小学",
          "value": 1,
          disabled: false
        }, {
          "label": "中学",
          "value": 2,
          disabled: false
        }, {
          "label": "高中",
          "value": 3,
          disabled: false
        }, {
          "label": "九年一贯制",
          "value": 4,
          disabled: false
        }, {
          "label": "特殊教育",
          "value": 5,
          disabled: false
        }],
        // 表单详细信息
        formData: {
          formTitle: '',
          number: 0,
          // 表单作用的学校
          schools: [],
          // 题目
          formlist: [{
            title: '',
            type: 1,
            category: null,
            number: 0,
            key: Date.now(),
            // type为1是选择题，下面储存选项
            optionlist: [{
              option: '',
              reason: false,
              checked: false,
              key: Date.now(),
            }, {
              option: '',
              reason: false,
              checked: false,
              key: Date.now(),
            }],
          }]
        },
        typeOptions: [{
          "label": "选择",
          "value": 1
        }, {
          "label": "简答",
          "value": 2
        }],
        categoryOptions: [],
      }
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {
      this.fullscreenLoading = true;
      listSchool(this.querySchoolParams).then(result => {
        let data = result.rows
        for (let i = 0; i < data.length; i++) {
          this.schoollist.push({
            key: data[i].id,
            label: data[i].name,
            type: data[i].type - 0,
            nature: data[i].nature !== 0
          })
        }

        let map = new Map();
        for (const scItem of this.schoollist) {
          map.set(scItem.type, 0)
        }

        for (const scOption of this.schoolOptions) {
          if (map.get(scOption.value) !== 0) {
            scOption.disabled = true
          }
        }
        this.fullscreenLoading = false;
      })
      this.getDicts("question_category").then(response => {
        this.categoryOptions = response.data;
      });
    },
    methods: {
      chooseSchool() {
        let old = JSON.parse(JSON.stringify(this.schoollist))
        let left = []
        for (let item of old) {
          if (this.schoolskey.indexOf(item.key) === -1) {
            left.push(item)
          }
        }

        this.schoolcategory = []
        for (let item of this.schoolOptions.filter(e => e.disabled === false)) {
          let find = left.find(e => {
            return e.type === item.value
          })
          if (find === undefined) {
            this.schoolcategory.push(item.value)
          }
        }
        // console.log(32132)
        // this.schoolcategory = [];
        // var list = [];
        // this.schoollist.forEach(value => {
        //   if (this.schoolskey.indexOf(value.key) === -1) {
        //     list.push(value.type)
        //   }
        // })
        // var type = []
        // this.schoolOptions.forEach(value => {
        //   if (list.indexOf(value.value) === -1) {
        //     type.push(value.value)
        //   }
        // })
        // type.forEach(value => {
        //   var x = 0;
        //   this.schoollist.forEach(value1 => {
        //     if (value === value1.type)
        //       x++;
        //   })
        //   if (x > 0)
        //     this.schoolcategory.push(value)
        // })
        setTimeout(function () {
          document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
            v.getElementsByClassName("el-checkbox__label").forEach(v => {
              v.setAttribute('title', v.textContent)
            })
          })
        }, 500);
      },
      handle(time, type) {
        if (type) {
          var startAt = new Date(this.formData.schools[time].time);
          if (startAt < Date.now()) {
            this.formData.schools[time].time = null
            this.$message.error('时间设置错误请检查');
          }
        } else {
          var startAt = new Date(this.time);
          if (startAt < Date.now()) {
            this.time = null
            this.$message.error('时间设置错误请检查');
          }
        }
      },
      addtab: function (vale) {
        if (vale) {
          switch (this.tab) {
            case 1:
              if (this.formData.formlist.length <= 1)
                this.$alert('你还没有为表单添加问题', '警告', {
                  confirmButtonText: '确定',
                  closeOnClickModal: false,
                });
              else {
                this.tab++
                setTimeout(function () {
                  document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
                    v.getElementsByClassName("el-checkbox__label").forEach(v => {
                      v.setAttribute('title', v.textContent)
                    })
                  })
                }, 500);
              }
              break;
            case 2:
              if (this.schoolskey.length < 1)
                this.$alert('你还没有为表单添加对应的学校', '警告', {
                  confirmButtonText: '确定',
                  closeOnClickModal: false
                });
              else {
                this.tab++
              }
              //把选择的学校从临时key转为学校对象
              this.formData.schools = [];
              this.schoollist.forEach(value => {
                if (this.schoolskey.indexOf(value.key) !== -1)
                  this.formData.schools.push({
                    key: value.key,
                    label: value.label,
                    time: null
                  })
              })
              break;
          }
        } else this.tab--
      },
      // 添加问题前判空
      submitForm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          this.addFormlist()
        })
      },
      resetForm() {
        this.$refs['elForm'].resetFields()
      },
      // 添加问题
      addFormlist() {
        this.formData.formlist.push({
          title: '',
          type: 1,
          category: null,
          key: Date.now(),
          optionlist: [{
            option: '',
            reason: false,
            checked: false,
            key: Date.now(),
          }, {
            option: '',
            reason: false,
            checked: false,
            key: Date.now(),
          }],
        })
        this.formData.number++
      },
      // 添加问题选项
      addoptionlist() {
        this.formData.formlist[this.formData.number].optionlist.push({
          option: '',
          reason: false,
          checked: false,
          key: Date.now()
        });
      },
      // 删除问题的选项
      reomoptionlist(itme) {
        if (this.formData.formlist[this.formData.number].optionlist.length === 1) {
          this.$message.info("至少要有一个选项")
          // this.$alert('至少要有一个选项', '提示',
          //   {
          //     confirmButtonText: '确定',
          //     closeOnClickModal: false,
          // });
          return;
        }
        this.formData.formlist[this.formData.number].optionlist.splice(itme, 1)
      },
      // 删除问题
      reomopquestion(itme) {
        this.formData.number--
        this.formData.formlist.splice(itme, 1)
      },
      // 移动问题
      mobilequestion(itme, type) {
        this.formData.formlist[itme] = this.formData.formlist.splice(itme + (type ? 1 : -1), 1, this.formData.formlist[
          itme])[0];
      },
      // 修改学校类别把学校加入临时学校list
      schoolchange(vale) {
        this.schoolskey = [];
        this.schoollist.forEach(value => {
          if (this.schoolskey.indexOf(value.key) === -1) {
            if (vale.toString().indexOf(value.type) !== -1 || vale.toString().indexOf(value.nature) !== -1)
              this.schoolskey.push(value.key)
          }
        })
      },
      // 上传表单数据
      submitformdata() {
        this.fullscreenLoading = true;
        if (this.timetype === 0)
          this.formData.schools.forEach(value => value.time = this.time)
        try {
          if (this.timetype === 0)
            if (this.time === null) {
              this.$message.error("时间设置错误请检查")
              throw new Error("")
            }
          if (this.timetype === 1)
            this.formData.schools.forEach(value => {
              if (value.time === null) {
                this.$message.error("时间设置错误请检查")
                throw new Error("")
              }
            })
        } catch (e) {
          return;
        }
        console.log(JSON.stringify(this.formData))
        addForm(this.formData).then(response => {
          this.msgSuccess("新增成功");
          this.fullscreenLoading = false;
          this.$tab.closePage();
          this.$tab.refreshPage({
            path: "/form/index",
            name: "form"
          })
        });
      }
    },

  }

</script>

<style scoped>
  .app-container {
    background-color: #edf1f2;
    padding: 10px;
    min-height: calc(100vh - 35px)
  }

  ::v-deep.pagination-container .el-pagination {
    text-align: center;
    position: sticky;
  }

  ::v-deep.el-steps--simple {
    background: white;
  }

  ::v-deep.el-transfer :nth-child(3) div {
    border: 1px solid #00B3A8;
  }

  ::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header {
    border: 1px solid #00B3A8;
    background: #00B3A8;
  }

  ::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label {
    color: white;
  }

  ::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label span {
    color: white;
  }

  ::v-deep .el-transfer-panel {
    width: 300px;
  }

</style>
